--# Camera
Camera = class()

function Camera:init(eX,eY,eZ,lX,lY,lZ)
    self.eye = vec3(eX or 0, eY or 300, eZ or 400)
    self.lat = vec3(lX or 0, lY or 300, lZ or 0)
    self.dist = self.lat:dist(self.eye)
    self.angH = 90
    self.angV = -90
    self.fix = true
    self.crosshair = true
    self.touchid = 0
    self.prevTouchPos = vec2(0,0)
    self.xRot,self.yRot = 0,0
    self.stick = JoyStick(150,150,200)
end

function Camera:draw()
    self.angH = self.angH +(self.yt or 0)
    self.angV = self.angV + (self.xt or 0)
    
    self:moveLocal(self.stick.directionVec2.x*1.8,nil,self.stick.directionVec2.y*1.8)
    self.Z = (self.lat-self.eye):normalize()
    self.X = self.Z:cross(vec3(0,1,0)):normalize()
    self.Y = self.X:cross(self.Z):normalize()
    self.angV = math.min(-1,math.max(-179,self.angV))
    if self.fix then
        self.eye = -self:rotatePoint() + self.lat
    else
        self.lat =  self:rotatePoint() + self.eye
    end
    self.stick:draw()
    
    camera(self.eye.x, self.eye.y, self.eye.z,self.lat.x, self.lat.y, self.lat.z)
    
    self.mat = modelMatrix()*viewMatrix()*projectionMatrix()
end

function Camera:touched(touch)
    self.stick:touched(touch)
    if touch.x > 220 and touch.y > 220 then
        if touch.state == BEGAN then
            if self.touchid == 0 then
                self.prevTouchPos = vec2(touch.x, touch.y)
                self.touchid = touch.id
            end
        elseif touch.state == MOVING then
            if self.touchid == touch.id then
                local delta = (vec2(touch.x, touch.y) - self.prevTouchPos) / 2
                self:turn(delta.y,delta.x)
                
                self.prevTouchPos = vec2(touch.x, touch.y)
            end
        else
            self.xt ,self.yt = 0,0
            self.touchid = 0
        end
    end
end

function Camera:moveLocal(x,y,z)
    if x and x ~= 0 then
        local xVel = self.X * x
        self.eye = self.eye + xVel
        self.lat = self.lat + xVel
    end
    if y and y ~= 0 then
        local yVel = self.Y * y
        self.eye = self.eye + yVel
        self.lat = self.lat + yVel
    end
    if z and z ~= 0 then
        local zVel = self.Z * z
        self.eye = self.eye + zVel
        self.lat = self.lat + zVel
    end
end

function Camera:rotatePoint()
    -- calculate y and z from angV at set distance
    local y = math.cos(math.rad(self.angV))*self.dist
    local O = math.sin(math.rad(self.angV))*self.dist
    -- calculate x and z from angH using O as the set distance
    local x = math.cos(math.rad(self.angH))*O
    local z = math.sin(math.rad(self.angH))*O
    return vec3(x,y,z)
end

function Camera:turn(xt,yt)
    self.xt,self.yt = xt,yt
end

